<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled" v-if="this.isEdit === false">
      <a-form-model ref="form" :model="queryParam"  :rules="validatorRules" slot="detail">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="First Name"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="firstName" >
              <a-input placeholder="" v-model="queryParam.firstName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="Last Name"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lastName">
              <a-input placeholder="" v-model="queryParam.lastName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="invoiceSearchQuery" icon="search">Search</a-button>
              <a-button type="primary" @click="invoiceSearchReset" icon="reload" style="margin-left: 8px">Reset</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form-model>
      <a-divider />
    </j-form-container>
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form1"    :model="model"  :rules="validatorRules1" slot="detail">
      <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onTableSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="description" slot-scope="text, record">
          <editable-cell :text="text" :id="record.id" :type=1 @change="onDescriptionChage"/>
        </template>
        <template slot="price" slot-scope="text, record">
          <editable-cell :text="text" :id="record.id"  :type=2 @change="onPriceChage" />
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>

      </a-table>

        <!--<a-table
          v-if="this.isEdit === true"
          ref="table"
          size="middle"
          :scroll="{x:true}"
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          :loading="loading"
          class="j-table-force-nowrap"
          @change="handleTableChange">

          <template slot="description" slot-scope="text, record">
            <editable-cell :text="text" :id="record.id" :type=1 @change="onDescriptionChage"/>
          </template>
          <template slot="price" slot-scope="text, record">
            <editable-cell :text="text" :id="record.id"  :type=2 @change="onPriceChage" />
          </template>
          <template slot="htmlSlot" slot-scope="text">
            <div v-html="text"></div>
          </template>
          <template slot="imgSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
            <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
          </template>

        </a-table>-->
    </div>

    <div style="padding-top: 15px;">
        <a-row :gutter="24">
            <a-col :span="6">
              <div align="left" style="padding-left: 12px;margin-bottom: -30px;">
                <a-form-model-item labelAlign="right" label="Subtotal" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="subtotal">

                </a-form-model-item>
              </div>
            </a-col>
            <a-col :span="4" :offset="14" >
               <div style="padding-left: 20px;" v-if="this.model.subtotal > 0 ">${{this.formatNumber(this.model.subtotal)}}</div>
              <div style="padding-left: 20px;" v-if="this.model.subtotal <= 0 ">-</div>
            </a-col>
        </a-row>
      <a-divider />


      <a-row :gutter="24" >
        <a-col :span="6">
          <div align="left" style="padding-left: 12px;margin-bottom: -30px;">
            <a-form-model-item labelAlign="right" label="Discount" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="discountType">
              <j-dict-select-tag type="list" v-model="model.discountType" :triggerChange="true" @change="onDisccountTypeChange" dictCode="discountType" placeholder="" />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="6">
          <div align="left" style="margin-bottom: -30px;">
            <a-form-model-item labelAlign="right" label="" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="discount">
              <a-input-number v-model="model.discount" :min = "0" placeholder="" @change="onDisCountChange"  />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="4" :offset="8" >
          <div style="padding-left: 20px;" v-if="this.model.discountTotal > 0 " >-${{this.formatNumber(this.model.discountTotal)}}</div>
          <div style="padding-left: 20px;" v-if="this.model.discountTotal <= 0 ">-</div>

        </a-col>
      </a-row>
      <a-divider />
      <a-row :gutter="24" style="margin-bottom: -30px;">
        <a-col :span="6">
          <div align="left" style="padding-left: 12px;">
            <a-form-model-item labelAlign="right" label="Total after tax" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="tax">
              <j-dict-select-tag type="list" v-model="model.tax" dictCode="tax" placeholder="" :triggerChange="true" @change="onTaxChange" />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="4" :offset="14" >
          <div style="padding-left: 20px;" v-if="this.model.subtotal > 0 " >${{this.formatNumber(this.model.taxTotal)}}</div>
          <div style="padding-left: 20px;" v-if="this.model.subtotal <= 0 " >-</div>
        </a-col>
      </a-row>

      <a-divider />
      <a-row :gutter="24" >
        <a-col :span="6">
          <div align="left" style="padding-left: 12px;margin-bottom: -30px;">
            <a-form-model-item labelAlign="right" label="Credit" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="credit">
                 <a-input-number v-model="model.credit" placeholder="" :disabled="this.isEdit" :max="model.studentCredit" style="width: 100%" @change="onCreditChange" />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="6">
          <div align="left" style="margin-bottom: -30px;">
            <a-form-model-item labelAlign="right" label="" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="">
                 <a-input-number v-model="model.studentCredit" placeholder="" :disabled="true" />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="4" :offset="8" >
          <div style="padding-left: 20px;" v-if="this.model.creditTotal > 0 ">-${{this.formatNumber(this.model.creditTotal)}}</div>
          <div style="padding-left: 20px;"  v-if="this.model.creditTotal <= 0 ">-</div>
        </a-col>
      </a-row>
      <a-divider />
      <a-row :gutter="24">
        <a-col :span="6">
          <div align="left" style="padding-left: 12px;margin-bottom: -30px;">
            <a-form-model-item labelAlign="right" label="Total" style="font-weight: bold;" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="total">

            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="4" :offset="14" >
          <div style="padding-left: 20px;font-weight: bold;"  v-if="this.model.total > 0 ">${{this.formatNumber(this.model.total)}}</div>
          <div style="padding-left: 20px;font-weight: bold;"  v-if="this.model.total <= 0 ">-</div>
        </a-col>
      </a-row>
      <a-divider />
      <a-row :gutter="24">
        <a-col :span="6">
          <div align="left" style="padding-left: 12px;margin-bottom: -30px;">
            <a-form-model-item labelAlign="right" label="Total" style="font-weight: bold;"  :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="credit">
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="4" :offset="10">
          <div align="left" style="margin-bottom: -30px;float: right">
            <a-form-model-item labelAlign="right" label="" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="currency">
              <j-dict-select-tag type="list" v-model="model.currency" dictCode="amountSymbol" placeholder="" style="width: 120px;" :triggerChange="true" @change="onSymbolChange" />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="4"  >
          <div align="left" style="margin-bottom: -30px;float: left">
              <a-form-model-item labelAlign="right"  label="" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="currencyAmount">
                <a-input-number v-model="model.currencyAmount" style="width: 130px;" placeholder="" :disabled="false" />
              </a-form-model-item>
          </div>
         <!-- <div style="padding-left: 20px;" v-if="this.model.creditTotal > 0 ">-${{this.formatNumber(this.model.creditTotal)}}</div>
          <div style="padding-left: 20px;"  v-if="this.model.creditTotal <= 0 ">-</div>-->
        </a-col>
      </a-row>

      <a-divider />

      <a-row :gutter="24" style="margin-bottom: -30px;">
        <a-col :span="6">
          <div align="left" style="padding-left: 12px;">
            <a-form-model-item labelAlign="right" label="Payment Due Date" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="lastPayTime">
              <a-date-picker
                v-model="model.lastPayTime"
                valueFormat="YYYY-MM-DD"
                style="width: 100%;"
              />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="4" :offset="14" >
          <!--  <div style="padding-left: 20px;" v-if="this.model.subtotal > 0 " >${{this.formatNumber(this.model.taxTotal)}}</div>
            <div style="padding-left: 20px;" v-if="this.model.subtotal <= 0 " >-</div>-->
        </a-col>
      </a-row>
      <a-divider />

      <a-row :gutter="24">
        <a-col :span="12">
          <div align="left" style="margin-bottom: -30px;">
            <a-form-model-item labelAlign="right" label="Memo" :labelCol="labelCol2" :wrapperCol="wrapperCol3" prop="remarks">
              <a-textarea placeholder="" v-model="model.remarks" :rows="4" />
            </a-form-model-item>
          </div>
        </a-col>

      </a-row>
    </div>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>


  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import EditableCell from "@views/sistersophie/invoice/modules/EditableCell"
  import JInput from '@/components/jeecg/JInput'

  export default {
    name: 'InvoiceInfoForm',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      EditableCell,
      JInput
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        disableMixinCreated:true,
        studentId:0,
        isEdit:false,
        model:{
          tax:"13",
          subtotal:0,
          taxTotal:0,
          creditTotal : 0,
          discount:0,
          total:0,
          discountType:1,
          discountTotal:0,
          studentCredit:0,
          credit:0,
          lastPayTime:'',
          currency:'CAD-$',
          currencyAmount:0,
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        labelCol1: {
          xs: { span: 24 },
          sm: { span: 12 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol1: {
          xs: { span: 24 },
          sm: { span: 12 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 14 },
        },
        wrapperCol3: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          firstName: [
            { required: true, message: 'Please enter first name!'},
          ],
          lastName: [
            { required: false, message: 'Please enter last name!'},
          ],
        },
        validatorRules1: {
          tax: [
            { required: true, message: 'Please select tax info!'},
          ],
          lastPayTime: [
            { required: true, message: 'Please select due date!'},
          ],
          currency: [
            { required: true, message: 'Please select currency!'},
          ],
          currencyAmount: [
            { required: true, message: 'Please enter currencyAmount!'},
          ]
        },
        columns: [
           {
             title: '#',
             dataIndex: '',
             key:'rowIndex',
             width:40,
             align:"center",
             customRender:function (t,r,index) {
               return parseInt(index)+1;
             }
           },
          {
            title:'First Name',
            align:"center",
            width:80,
            dataIndex: 'firstName'
          },
          {
            title:'Last Name',
            align:"center",
            width:80,
            dataIndex: 'lastName'
          },
          {
            title:'Chinese Name/WeChat Name',
            align:"center",
            width:80,
            dataIndex: 'chineseName'
          },
          {
            title:'Course Name',
            align:"center",
            width:100,
            dataIndex: 'courseName'
          },
          {
            title:'Description',
            align:"center",
            width:120,
            dataIndex: 'description',
            scopedSlots: { customRender: 'description' },
          },
          {
            title:'Price',
            align:"center",
            width:140,
            dataIndex: 'priceFormat',
          }
        ],
        url: {
          list:"/sistersophie/courseStudentInfo/invoice/list",
          add: "/sistersophie/invoiceInfo/add",
          edit: "/sistersophie/invoiceInfo/edit",
          queryById: "/sistersophie/invoiceInfo/queryById",
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      formatNumber(value) {
        value += '';
        const list = value.split('.');
        const prefix = list[0].charAt(0) === '-' ? '-' : '';
        let num = prefix ? list[0].slice(1) : list[0];
        let result = '';
        while (num.length > 3) {
          result = `,${num.slice(-3)}${result}`;
          num = num.slice(0, num.length - 3);
        }
        if (num) {
          result = num + result;
        }
        return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
      },
      onDescriptionChage(val,id){
        if(this.dataSource && this.dataSource.length > 0) {
          for (let j = 0; j < this.dataSource.length; j++) {
            let record = this.dataSource[j];
            if(record.id === id){
              record.description = val;
            }
          }
        }
      },
      onPriceChage(val,id){
        if(this.dataSource && this.dataSource.length > 0) {
          for (let j = 0; j < this.dataSource.length; j++) {
            let record = this.dataSource[j];
            if(record.id === id){
              record.price = val;
             // this.dataSource[j] = record;
            }
          }
        }
        if(this.model.selectionRows && this.model.selectionRows.length > 0) {
            console.info('onPriceChage');
            console.info(this.model.selectionRows);
            this.calculationAmount();
          }
        },
      onCreditChange(val){
        if(val >= 0){
          this.model.credit = val;
        }else{
          this.model.credit = 0;
        }
        this.calculationAmount();
      },
      onDisccountTypeChange(val){
        this.model.discountType = val;
        this.calculationAmount();
      },
      onDisCountChange(val){
        if(this.model.discount >= 0){
          this.model.discount = val;
        }else{
          this.model.discount = 0;
        }
        this.calculationAmount();
      },
      onTaxChange(val){
        this.model.tax = val;
        this.calculationAmount();
      },
      onSymbolChange(val){
        this.model.currency = val;
      },
      onTableSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
        this.model.selectionRows = selectionRows;
        this.calculationAmount();
        if(this.model.selectionRows && this.model.selectionRows.length > 0) {
          //加载学生 credit信息
          this.studentId = this.model.selectionRows[0].studentId;
          this.loadStudentCredit();
        }else{
          this.model.studentCredit = 0;
        }
      },
      loadStudentCredit(){
        let httpurl = "/sistersophie/accountInfo/queryByStudent";
        let params = {};
        params.studentId = this.studentId;
        httpAction(httpurl,params,'post').then((res)=>{
          if(res.success){
            this.model.studentCredit = res.result.availableAmount;
          }
        }).finally(() => {

        })
      },
      calculationAmount(){
        if(this.model.selectionRows && this.model.selectionRows.length > 0){
            //计算Subtotal
            let subtotal = 0;
            let discountTotal = 0;
            for(let j = 0; j < this.model.selectionRows.length; j++) {
              let row = this.model.selectionRows[j];
              subtotal = subtotal + row.price;
              if (row.price > 0) {
                let discountCoursePrice = 0;
                //折扣方式为百分比
                if (this.model.discountType === '1' || this.model.discountType === 1) {//%
                  let discountPersent = this.model.discount === 0 ? 0 : this.model.discount / 100;
                  discountCoursePrice = row.price * (discountPersent);
                   //课程实付价格
                  this.model.selectionRows[j].actualPrice = row.price - discountCoursePrice.toFixed(2);
                } else if (this.model.discountType === '2' || this.model.discountType === 2) {//$
                  let persent = 1 / this.model.selectionRows.length; //固定金额时 每个课程的折扣金额平分
                  let discount = Number(this.model.discount);
                  //不四舍五入
                  if((j+1) != this.model.selectionRows.length){
                    discountCoursePrice = Math.floor(discount * persent * 100) / 100;
                  }else {
                    discountCoursePrice = (discount - discountTotal);
                  }
                  this.model.selectionRows[j].actualPrice = row.price - discountCoursePrice;
                }else{
                  this.model.selectionRows[j].actualPrice = row.price;
                  discountCoursePrice = 0;
                }

                if (discountCoursePrice > 0) {
                  discountTotal = discountTotal + discountCoursePrice;
                }

              }
            }
            console.info(this.model);
            this.model.discountTotal = discountTotal.toFixed(2);
            this.model.subtotal = subtotal.toFixed(2);
            //计算tax金额
            let tax = this.model.tax / 100;
            let taxTotal = (this.model.subtotal - this.model.discountTotal) * (1 + tax);
            taxTotal = taxTotal.toFixed(2);
            this.model.taxTotal = taxTotal;
            this.model.total =  Number(this.model.taxTotal).toFixed(2);
            if(this.model.credit >= 0){
              let credit = Number(this.model.credit);
              this.model.creditTotal = credit;
              this.model.total = (Number(this.model.total) -  Number(this.model.creditTotal)).toFixed(2);
            }
        }else{
          this.model.subtotal = 0;
          this.model.taxTotal = 0;
          this.model.total = 0;
          this.model.discountTotal = 0;
          this.model.credit=0;
          this.model.studentCredit = 0;
          this.studentId = 0;
          this.model.tax = "13";
          this.model.creditTotal = 0;
          this.$message.warning("Please select student and course information")
        }
      },
      add () {
        this.isEdit = false;
        this.model = Object.assign({}, this.modelDefault);
        this.visible = true;
        this.queryParam.payStatus = '3';
        this.model.isEdit = 0;
      },
      edit (record) {
        this.isEdit = true;
        this.model = Object.assign({}, this.modelDefault);
        console.info(record);
        this.model.id = record.id;
        if(record.lastPayTime && record.lastPayTime != ''){
          this.model.lastPayTime = record.lastPayTime;
        }
        this.model.subtotal = Number(record.amount).toFixed(2);
        this.model.tax = record.tax;
        this.model.taxTotal = Number(record.taxAfterAmount).toFixed(2);
        this.model.discountType = record.discountType;
        this.model.discount = record.discount;
        this.model.discountTotal = Number(record.discountAmount).toFixed(2);
        this.model.credit = record.credit;
        this.model.total = Number(record.invoiceAmount).toFixed(2);
        this.model.remarks = record.remarks;
        this.model.creditTotal = Number(record.credit).toFixed(2);
        this.model.isEdit = 1;
        this.model.currency = record.currency;
        this.model.currencyAmount = record.currencyAmount;

        this.studentId = record.studentId;
        //this.model = Object.assign({}, record);
        this.loadStudentCredit();

        this.queryParam.payStatus = '4';
        this.queryParam.studentId = record.studentId;
        this.queryParam.invoiceId = record.id;
        this.queryParam.isEdit = 1;

        this.loadEditData();
        //加载数据源
        this.visible = true;
      },
      invoiceSearchQuery() {
        this.queryParam.payStatus = '3';
        this.$refs.form.validate(valid => {
            if (valid) {
              this.loadData(1);
            }
        });
      },
      invoiceSearchReset() {
        this.queryParam = {};
        this.queryParam.payStatus = '3';
        this.loadData(1);
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form1.validate(valid => {
          if (valid) {
            if(this.model.selectionRows && this.model.selectionRows.length > 0) {
              //开始组装请求参数
              let params = {};
              params.records = this.model.selectionRows;
              params.subtotal = this.model.subtotal;
              params.tax = this.model.tax;
              params.taxTotal = this.model.taxTotal;
              params.discountType = this.model.discountType;
              params.discount = this.model.discount;
              params.discountTotal = this.model.discountTotal;
              params.credit = this.model.credit;
              params.total = this.model.total;
              params.remarks = this.model.remarks;
              params.lastPayTime = this.model.lastPayTime;
              params.currency = this.model.currency;
              params.currencyAmount = this.model.currencyAmount;
              that.confirmLoading = true;
              let httpurl = '';
              let method = '';
              if(!this.model.id){
                httpurl+=this.url.add;
                method = 'post';
              }else{
                params.id = this.model.id;
                httpurl+=this.url.edit;
                method = 'put';
              }
              httpAction(httpurl,params,method).then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  that.$emit('ok');
                }else{
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
              })
            }else{
              this.$message.warning("Please select student and course information")
            }
          }
        })
      },
      loadEditData(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records||res.result;
            //this.selectedRowKeys = [];
            let tempArray = [];
            for(var j = 0,len = this.dataSource.length; j < len; j++){
              let item = this.dataSource[j];
              if(item.isSelect == 1){
                  this.selectedRowKeys.push(item.id + "");
                  tempArray.push(item);
                }
            }
            console.info('selectedRowKeys',this.selectedRowKeys);
            console.info('tempArray',tempArray);
            this.model.selectionRows = tempArray;
            console.info('this.model.selectionRows',this.model.selectionRows);


            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
          this.loading = false;
        })
      },
    }
  }
</script>
<style>

.table-page-search-submitButtons {
  display: block;
  margin-bottom: 24px;
  white-space: nowrap;
  padding-top: 4px;
}
</style>